package com.itheima.health.controller;

import com.itheima.health.common.MessageConst;
import com.itheima.health.common.RedisConst;
import com.itheima.health.entity.Result;
import com.itheima.health.pojo.Member;
import com.itheima.health.pojo.User;
import com.itheima.health.service.MemberService;
import com.itheima.health.service.UserService;
import io.swagger.annotations.Api;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.util.DigestUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.time.LocalDateTime;
import java.util.Date;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * 登录控制器
 */
@RestController
@RequestMapping("/mobile/login")
@Slf4j
@Api(tags = "手机端登录接口")
public class MobileLoginController {
    @Autowired
    private RedisTemplate<Object, Object> redisTemplate;
    @Autowired
    private MemberService memberService;
    @Autowired
    private UserService userService;

    /* 移动端用户登录 */
    @PostMapping("/smsLogin")
    public Result smsLogin(@RequestBody Map map, HttpSession session) {
        String telephone = map.get("telephone").toString();
        String code = map.get("validateCode").toString();
        String trueCode = (String) redisTemplate.opsForValue().get(telephone);
        if (!code.equals(trueCode)) {
            return new Result(false, MessageConst.VALIDATECODE_ERROR);
        }
        redisTemplate.delete(telephone);
        Member member = memberService.findByTelephone(telephone);
        if (member == null) {
            member = new Member();
            member.setPhoneNumber(telephone);
            member.setRegTime(new Date());
            memberService.save(member);
        }
        session.setAttribute("member", member.getId());
        return new Result(true, MessageConst.LOGIN_SUCCESS, member);
    }
}
